#include <dirent.h>
#include <sys/types.h>
#include <errno.h>
#include <stdlib.h>
#include<string.h>
#include <fcntl.h>
#include <unistd.h>
#include<stdio.h>

#include"logger.h"
#include"get_ds18b20_detals.h"

int get_temperature(float *temp)
{
	int               fd = -1;
	char              buf[128];            //看到buf要记得清除缓存区
	char              *ptr=NULL;
	DIR               *dirp = NULL;
	struct dirent     *direntp = NULL;
	char              w1_path[64]="/sys/bus/w1/devices/";
	char              chip_sn[32];
	int               found =0;

	dirp = opendir(w1_path);
	if(!dirp)
	{
		log_error("open folder %s failure :%s\n", w1_path, strerror(errno));
		return -1;
	}
	while(NULL != (direntp = readdir(dirp)))  //要记得加括号
	{
		if(strstr(direntp->d_name, "28-"))
		{
			strncpy(chip_sn, direntp->d_name, sizeof(chip_sn));
			found =1;
		}	
	}
	closedir(dirp);

	if(!found)
	{
		log_error("Can not find ds18b20 chipset\n");
		return -2;
	}
	//获取序列号得到文件夹路径
	strncat(w1_path, chip_sn, sizeof(w1_path)-strlen(w1_path));
	strncat(w1_path, "/w1_slave", sizeof(w1_path)-strlen(w1_path));
	log_debug("w1_path =%s\n", w1_path);

	fd = open(w1_path, O_RDONLY);
	log_debug("fd = %d\n", fd);
	if(fd<0)
	{
		log_error("open file failure: %s\n", strerror(errno));
		log_error("open file failure");
		return -3;

	}

	memset(buf, 0, sizeof(buf));
	if(read(fd, buf, sizeof(buf))<0)
	{
		log_error("read data from fd=%d failure: %s\n", fd, strerror(errno));
		return -4;
	}
	log_debug("buf: %s\n", buf);                //到这已经可以将完整的信息打印出来
	

	ptr = strstr(buf, "t=");                 //strstr（）函数是匹配字符串函数
	if(!ptr)                                //如果需要判断指针是否为空，一般把立即数NULL写在前面
	{
		log_error("Can not find t= string\n");
		return -5;
	}
	ptr += 2;
	log_debug("ptr:%s\n", ptr);
	
	*temp = atof(ptr)/1000;                 //atof函数是将字符串型的转化成浮点数
	log_debug("temprature: %f\n", *temp);

	close(fd);

	return 0;
}

void get_devid(char *id, int len)
{
	int sn = 1;
	snprintf(id, len, "rpi#%05d", sn);
}
